package com.crm.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.extra.servlet.ServletUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.crm.commons.exception.BusinessException;
import com.crm.commons.exception.enumVo.BussinessExceptionEnum;
import com.crm.entity.CrmActivity;
import com.crm.entity.CrmActivityRemark;
import com.crm.entity.CrmUser;
import com.crm.mapper.CrmActivityMapper;
import com.crm.mapper.CrmActivityRemarkMapper;
import com.crm.mapper.CrmUserMapper;
import com.crm.service.ICrmActivityService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.crm.util.HttpContext;
import com.crm.util.UUIDUtils;
import com.crm.vo.ActivityDetail;
import com.crm.vo.ActivityRemark;
import com.crm.vo.PageBean;
import com.crm.vo.SysActivity;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author junxian, dou
 * @since 2024-11-25
 */
@Service
public class CrmActivityServiceImpl extends ServiceImpl<CrmActivityMapper, CrmActivity> implements ICrmActivityService {

    @Resource
    private CrmActivityRemarkMapper remarkMapper;

    @Resource
    private CrmUserMapper crmUserMapper;

    @Override
    public void saveSysActivity(SysActivity activity) {
        activity.setId(UUIDUtils.getUUID());
        save(activity.getCrmActivity());
    }

    @Override
    public PageBean<CrmActivity> pageList(PageBean pageBean) {
        Map<String, String> map = pageBean.getQuery();
        String name = map.get("name").trim();
        String owner = map.get("owner").trim();
        String startTime = map.get("startTime").trim();
        String endTime = map.get("endTime").trim();
        String clueId = map.get("clueId");
        if (ObjectUtil.isNotEmpty(clueId)) {
            clueId = clueId.trim();
        }


        int pageSize = pageBean.getPageSize();
        int start = pageBean.getPageNum();

        Page<CrmActivity> page = new Page<>(start, pageSize);

        IPage<CrmActivity> iPage = this.baseMapper.pageList(page, name, owner, startTime, endTime,clueId);
        PageBean<CrmActivity> crmActivityPageBean = new PageBean<>(iPage.getTotal(), iPage.getRecords());
        return crmActivityPageBean;
    }

    @Override
    public void deleteById(List<String> id) {
        removeBatchByIds(id);
        //todo 其他操作
    }

    @Override
    public void updateWithId(SysActivity activity) {
        CrmActivity crmActivity = activity.getCrmActivity();
        updateById(crmActivity);
    }

    @Override
    public void fileDownload(List<String> id, HttpServletResponse response) {
        //查询所有的数据
        List<CrmActivity> activityList = this.baseMapper.list(id == null ? new ArrayList<>() : id);
        //创建exel文件，并且把activityList写入到excel文件中
        XSSFWorkbook wb = new XSSFWorkbook();
        XSSFSheet sheet = wb.createSheet("市场活动列表");
        XSSFRow row = sheet.createRow(0);
        XSSFCell cell = row.createCell(0);
        cell.setCellValue("ID");
        cell = row.createCell(1);
        cell.setCellValue("所有者");
        cell = row.createCell(2);
        cell.setCellValue("名称");
        cell = row.createCell(3);
        cell.setCellValue("开始日期");
        cell = row.createCell(4);
        cell.setCellValue("结束日期");
        cell = row.createCell(5);
        cell.setCellValue("成本");
        cell = row.createCell(6);
        cell.setCellValue("描述");
        cell = row.createCell(7);
        cell.setCellValue("创建时间");
        cell = row.createCell(8);
        cell.setCellValue("创建者");
        cell = row.createCell(9);
        cell.setCellValue("修改时间");
        cell = row.createCell(10);
        cell.setCellValue("修改者");
        //遍历数据
        if (!activityList.isEmpty()) {
            int i = 1;
            for (CrmActivity activity : activityList) {
                //每遍历出一个activity，生成一行
                row = sheet.createRow(i++);
                //每一行创建11列，每一列的数据从activity中获取
                cell = row.createCell(0);
                cell.setCellValue(activity.getId());
                cell = row.createCell(1);
                cell.setCellValue(activity.getOwner());
                cell = row.createCell(2);
                cell.setCellValue(activity.getName());
                cell = row.createCell(3);
                cell.setCellValue(activity.getStartDate());
                cell = row.createCell(4);
                cell.setCellValue(activity.getEndDate());
                cell = row.createCell(5);
                cell.setCellValue(activity.getCost());
                cell = row.createCell(6);
                cell.setCellValue(activity.getDescription());
                cell = row.createCell(7);
                cell.setCellValue(activity.getCreateTime());
                cell = row.createCell(8);
                cell.setCellValue(activity.getCreateBy());
                cell = row.createCell(9);
                cell.setCellValue(activity.getEditTime());
                cell = row.createCell(10);
                cell.setCellValue(activity.getEditBy());
            }
        }
        try {
            response.setContentType("application/octet-stream;charset=UTF-8");
            /**
             * 默认情况下，浏览器不允许跨域请求的JavaScript代码访问某些响应头信息。
             * 但是，通过Access-Control-Expose-Headers，服务器可以告诉浏览器哪些额外的头信息可以被JavaScript代码访问。
             */
            response.setHeader("Access-Control-Expose-Headers","Content-Disposition");
            response.setHeader("Content-Disposition", "attachment;filename=activityList.xlsx");

            ServletOutputStream outputStream = response.getOutputStream();
            wb.write(outputStream);
            //关闭资源
            wb.close();
            outputStream.flush();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void importActivity(MultipartFile file, CrmUser userInfo) {
        try {
            InputStream inputStream = file.getInputStream();
            HSSFWorkbook wb = new HSSFWorkbook(inputStream);
            HSSFSheet activityList = wb.getSheetAt(0);
            ArrayList<CrmActivity> crmActivities = new ArrayList<>();
            for (Row row : activityList) {
                if (row.getRowNum() == 0) continue;
                CrmActivity crmActivity = new CrmActivity();
                crmActivity.setId(UUIDUtils.getUUID());
                crmActivity.setOwner(userInfo.getId());
                for (Cell cell : row) {
                    String stringCellValue = cell.getStringCellValue();
                    int columnIndex = cell.getColumnIndex();
                    if (columnIndex == 0) {
                        crmActivity.setName(stringCellValue);
                    } else if (columnIndex == 1) {
                        crmActivity.setStartDate(stringCellValue);
                    } else if (columnIndex == 2) {
                        crmActivity.setEndDate(stringCellValue);
                    } else if (columnIndex == 3) {
                        crmActivity.setCost(stringCellValue);
                    } else if (columnIndex == 4) {
                        crmActivity.setDescription(stringCellValue);
                    }
                }
                crmActivities.add(crmActivity);
            }
            saveBatch(crmActivities);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public ActivityDetail getDetailActivity(String id) {
        CrmActivity byId = getById(id);
        if (ObjectUtil.isNull(byId)) {
            throw new BusinessException(BussinessExceptionEnum.ACTIVITY_NOT_EXISTS);
        }

        CompletableFuture<CrmActivity> future = CompletableFuture.supplyAsync(() -> {
            String owner = byId.getOwner();
            CrmUser crmUser = crmUserMapper.selectById(owner);
            byId.setOwner(crmUser.getName());
            return byId;
        });
        CompletableFuture<CrmActivity> future2 = CompletableFuture.supplyAsync(() -> {
            String userid = byId.getCreateBy();
            CrmUser crmUser = crmUserMapper.selectById(userid);
            byId.setCreateBy(crmUser.getName());
            return byId;
        });
        CompletableFuture<CrmActivity> future3 = CompletableFuture.supplyAsync(() -> {
            String editId = byId.getEditBy();
            CrmUser crmUser = crmUserMapper.selectById(editId);
            byId.setEditBy(crmUser.getName());
            return byId;
        });

        CompletableFuture.allOf(future, future2,future3);
        LambdaQueryWrapper<CrmActivityRemark> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CrmActivityRemark::getActivityId,byId.getId());
        List<CrmActivityRemark> crmActivityRemarks = remarkMapper.selectList(wrapper);
        List<ActivityRemark> activityRemarkList = crmActivityRemarks.stream().map(crmActivityRemark -> {
            CrmUser crmUser1 = crmUserMapper.selectById(crmActivityRemark.getCreateBy());
            ActivityRemark activityRemark = new ActivityRemark(crmActivityRemark, crmUser1);
            return activityRemark;
        }).collect(Collectors.toList());

        return new ActivityDetail(byId,activityRemarkList);
    }
}
